#include "MyDelegate.h"

#include <QComboBox>
#include <QTableWidgetItem>
#include <QLineEdit>

MyDelegate::MyDelegate(QObject *parent) : QStyledItemDelegate(parent)
{ }

QWidget *MyDelegate::createEditor(
        QWidget *parent,
        const QStyleOptionViewItem &option,
        const QModelIndex &index) const
{
    if(index.row() == 0 && index.column() == 1) {
        QComboBox *comboBox = new QComboBox(parent);
        for(int i = 0; i < 5; i++) {
            comboBox->addItem(QString("%1").arg(i), QVariant(i));
        }
        return comboBox;
    }
    else {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
}

void MyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if(index.row() == 1 && index.column() == 2) {
        if(QComboBox* comboBox = qobject_cast<QComboBox*>(editor)) {
            QVariant value = index.model()->data(index, Qt::EditRole);
            int index = comboBox->findData(value);
            if(index != -1) {
                comboBox->setCurrentIndex(index);
            }
        }
        return;
    }
    else {
        return QStyledItemDelegate::setEditorData(editor, index);
    }
}

void MyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if(index.row() == 0 && index.column() == 1) {
        if(QComboBox* comboBox = qobject_cast<QComboBox*>(editor)) {
            model->setData(index, comboBox->currentData());
        }
        return;
    }
    else {
        return QStyledItemDelegate::setModelData(editor, model, index);
    }
}
